package org.flash.display{
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.system.*;

	public class LoaderChild extends Loader {
		private var _complete:Function;
		private var _progress:Function;
		private var _history:Function;
		private var _path:String;
		private var _status:Boolean;
		private var _preload:Boolean;

		public function LoaderChild(path:String, complete:Function = null, progress:Function = null,
									history:Function = null, bool:Boolean = false){
			_path = path;
			_complete = complete;
			_progress = progress;
			_history = history;
			_preload = bool;
			this.load(new URLRequest(_path));
		}

		override public function load(request:URLRequest, context:LoaderContext = null):void {
			super.load(request, context);
			if (!this._preload && LoadChildInfo.loaderList != null){
				LoadChildInfo.mainLoaderStatus = true;
				LoadChildInfo.loaderList.stop();
			}
			//历吏路径
			if (_history != null){
				if (LoadChildInfo.historyArray.indexOf(this._path) == -1){
					_history(false);
				} else {
					_history(true);
				}
			}
			this.contentLoaderInfo.addEventListener(Event.COMPLETE, this.loadComplete);
			this.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.loadProgress);
			this.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.loadError);
		}

		/**加载完成*/
		private function loadComplete(event:Event):void {
			if (LoadChildInfo.historyArray.indexOf(this._path) == -1){
				LoadChildInfo.historyArray.push(this._path);
			}
			if (_complete != null){
				_complete(this);
			}
			if (!this._preload && LoadChildInfo.loaderList != null){
				LoadChildInfo.mainLoaderStatus = false;
				LoadChildInfo.loaderList.start();
			}
			this.depose();
		}

		/**加载进度*/
		private function loadProgress(event:ProgressEvent):void {
			if (_progress != null){
				_progress(event.target.bytesLoaded / event.target.bytesTotal * 100);
			}
		}

		/**销毁*/
		private function depose():void {
			this.contentLoaderInfo.removeEventListener(Event.COMPLETE, this.loadComplete);
			this.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, this.loadProgress);
			this.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.loadError);
			_complete = null;
			_progress = null;
			_history  = null;
		}

		/**卸载并停止执行已加载的*/
		override public function unloadAndStop(bool:Boolean = true):void {
			super.unloadAndStop(bool);
			if (this._status){
				this._status = false;
				this.close();
				this.depose();
			}
		}

		/**IO出错*/
		private function loadError(event:IOErrorEvent):void {
			trace("Error: Load not find path for:" + _path);
		}
	}
}